package com.umeox.watch.moto.camera;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.google.android.cameraview.CameraView;
import com.umeox.moto.common.utils.AndroidUtils;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.util.UToast;
import com.umeox.watch.moto.camera.adapter.FilterViewAdapter;
import com.umeox.watch.moto.camera.bean.FilterView;
import com.umeox.watch.moto.camera.utils.CameraUtils;
import com.umeox.watch.moto.camera.utils.HorizontalItemDecoration;
import com.umeox.watch.moto.camera.view.CaptureAnimView;
import com.umeox.watch.moto.dataservice.constants.Constants;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("NewApi")
public class CameraActivity extends ThemeAppCompatActivity implements View.OnClickListener, CaptureAnimView.AnimationListener , FilterViewAdapter.ItemClickListener{

    private static final String TAG = CameraActivity.class.getSimpleName();

    public static final Uri CONTENT_URI = Uri.parse("content://com.umeox.watch.moto.galleryProvider/gallery");
    public static final int MAX_STORAGE_FREE = 50 * 1024 * 1024;
    private CameraView mCameraView;
    private FrameLayout mAnimContainer;

    private final BroadcastReceiver mVideoCallReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CameraActivity.this.finish();
        }
    };
    private boolean mResume;
    private Handler mBackgroundHandler;
    private Context mContext;
    private View mTakePhotoBtn;
    private View mSwitchBtn;
    private View mFilterIb;

    private RecyclerView mFilterRv;
    private FilterViewAdapter mFilterViewAdapter;

    private MediaPlayer mMediaPlayer;

    private List<FilterView> filterViewList = new ArrayList<>();

    private String[] filterViews;

    private ImageView mFilterPreviewIv;


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        mContext = getApplicationContext();
        mCameraView = findViewById(R.id.texture);
        mCameraView.addCallback(mCallback);
        mAnimContainer = findViewById(R.id.anim_container);
        mSwitchBtn = findViewById(R.id.camera_switch_button);
        mTakePhotoBtn = findViewById(R.id.camera_takepicture_button);
        mFilterIb = findViewById(R.id.filter_ib);
        mFilterRv = findViewById(R.id.filter_rv);
        mFilterPreviewIv = findViewById(R.id.filter_preview_iv);

        mSwitchBtn.setOnClickListener(this);
        mTakePhotoBtn.setOnClickListener(this);
        mFilterIb.setOnClickListener(this);
        mFilterPreviewIv.setOnClickListener(this);
        mCameraView.setOnClickListener(this);
        mSwitchBtn.setVisibility(View.GONE);


       findViewById(R.id.gallery_button).setOnClickListener(v -> {
           ComponentName componentName = new ComponentName("com.umeox.watch.moto.gallery", "com.umeox.watch.moto.gallery.ui.AlbumListActivity");
           Intent intent = new Intent(Intent.ACTION_MAIN);
           intent.addCategory(Intent.CATEGORY_LAUNCHER);
           intent.setComponent(componentName);
           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
           mContext.startActivity(intent);
       });

        initFilterRv();

       registerVideoCallReceiver();
    }

    private void initFilterRv() {
        filterViewList.clear();
        filterViews = getResources().getStringArray(R.array.filter_view_arr);
        String[] filterViewThumbs = getResources().getStringArray(R.array.filter_view_thumb_arr);
        for (String resName : filterViewThumbs) {
            FilterView filterView = new FilterView();
            filterView.setResId(getResId(resName));
            filterView.setSelected(false);
            filterViewList.add(filterView);
        }

        mFilterViewAdapter = new FilterViewAdapter(filterViewList, this);
        mFilterRv.addItemDecoration(new HorizontalItemDecoration(8));
        mFilterRv.setAdapter(mFilterViewAdapter);
    }

    private int getResId(String name) {
        return getResources().getIdentifier(name, "drawable", mContext.getPackageName());
    }



    private Handler getBackgroundHandler() {
        if (mBackgroundHandler == null) {
            HandlerThread thread = new HandlerThread("background");
            thread.start();
            mBackgroundHandler = new Handler(thread.getLooper());
        }
        return mBackgroundHandler;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    private final CameraView.Callback mCallback = new CameraView.Callback() {

        @Override
        public void onPictureTaken(CameraView cameraView, final byte[] data) {
            startAnimation(data);
            getBackgroundHandler().post(() -> {

                if (mFilterViewAdapter.isNoItemSelected()) {
                    CameraUtils.saveImageFile(data, mContext, cameraView.getFacing() == CameraView.FACING_FRONT);
                } else {
                    //保存合并效果图
                    CameraUtils.saveFilterImageFile(data, mContext, getResId(filterViews[mFilterViewAdapter.indexOf()]), cameraView.getFacing() == CameraView.FACING_FRONT);
                }
            });
        }

        @Override
        public void onShutter() {
            playRingtone();
        }
    };


    private void registerVideoCallReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_RINGING_VIDEO_CALL);
        registerReceiver(mVideoCallReceiver, intentFilter);
    }


    @SuppressLint("CheckResult")
    public void startAnimation(byte[] data) {
        final BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 5;
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
        mAnimContainer.removeAllViews();
        CaptureAnimView captureAnimView = new CaptureAnimView(this);
        captureAnimView.setAnimationListener(this);
        captureAnimView.setImageBitmap(bitmap);
        mAnimContainer.addView(captureAnimView);
        captureAnimView.startAnimation();
    }


    public void playRingtone() {
        releaseMediaPlayer();
        mMediaPlayer = MediaPlayer.create(this, R.raw.camera);
        mMediaPlayer.start();

    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.camera_takepicture_button) {
            final long availableInternalMemory = AndroidUtils.getAvailableInternalMemory();
            if (availableInternalMemory <= MAX_STORAGE_FREE ) {
                UToast.showCustomToast(this, R.string.low_memory, Toast.LENGTH_LONG);
                return;
            }
            if (mCameraView != null) {
                mTakePhotoBtn.setEnabled(false);
                mTakePhotoBtn.postDelayed(() -> mTakePhotoBtn.setEnabled(true), 1200);
                mCameraView.takePicture();
            }
        } else if (v.getId() == R.id.camera_switch_button) {
            if (mCameraView != null) {
                mCameraView.setFacing(mCameraView.getFacing() == CameraView.FACING_BACK ? CameraView.FACING_FRONT : CameraView.FACING_BACK);
            }
        }else if (v.getId() == R.id.filter_ib) {
            mFilterRv.setVisibility(mFilterRv.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        } else if (v.getId() == R.id.texture || v.getId() == R.id.filter_preview_iv) {
            if (mFilterRv.getVisibility() == View.VISIBLE) {
                mFilterRv.setVisibility(View.GONE);
            }
        }

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mResume) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_MOVE_HOME) {
                mCameraView.takePicture();
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        mCameraView.start();
        mResume = true;
    }

    @Override
    protected void onPause() {
        mCameraView.stop();
        super.onPause();
        mResume = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        if (mVideoCallReceiver != null) {
            unregisterReceiver(mVideoCallReceiver);
        }
        if (mBackgroundHandler != null) {
            mBackgroundHandler.getLooper().quitSafely();
            mBackgroundHandler = null;
        }
    }


    @Override
    public void onAnimationEnd() {
        if (mAnimContainer != null) {
            mAnimContainer.removeAllViews();
        }
    }

    @Override
    public void onItemClicked(int position) {
        if (position == mFilterViewAdapter.indexOf()) { //点击的正好是当前选中的，则取消选中
            mFilterPreviewIv.setVisibility(View.GONE);
        } else {
            mFilterPreviewIv.setVisibility(View.VISIBLE);
            mFilterPreviewIv.setImageResource(getResId(filterViews[position]));
        }
        mFilterViewAdapter.addOrRemoveSelected(position);

    }
}
